package org.pearl.springbootsecurity.demo.MP.data;

import lombok.Data;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.expression.operators.relational.ItemsList;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.select.FromItem;
import net.sf.jsqlparser.statement.select.PlainSelect;
import org.pearl.springbootsecurity.demo.entity.DataPermission;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by TD on 2021/11/3
 *  权限处理器。根据自己的框架自定义实现
 */
@Data
public class PearlDataScopeHandler extends AbstractDataScopeHandler {

    public PearlDataScopeHandler(PearlDataScopeProperties pearlDataScopeProperties) {
        this.defaultDeptFiled = pearlDataScopeProperties.deptField;
    }

    @Override
    public void buildUserEqualToExpression(PlainSelect plainSelect) {
        buildEqualToExpression(plainSelect, "create_user_id", new LongValue(123555L)); // 值
    }

    @Override
    public void buildDeptEqualToExpression(PlainSelect plainSelect, DataScopeMapperProperty dataScopeProperty) {
        buildEqualToExpression(plainSelect, defaultDeptFiled, new LongValue(001L));
    }

    @Override
    ItemsList renderInExpressionList() {
        // 1. 查询部门集合（本部门及下属部门）
        return new ExpressionList(
                // 部门集合实际应当从用户信息中获取
                Arrays.asList(
                        new LongValue("001"),
                        new LongValue("002"),
                        new LongValue("003")
                ));
    }

    @Override
    public DynamicDataPermission renderDataPermission(Object obj) {
        // 1. 数据库或者缓存根据当前用户角色查询拥有的数据权限值
        DataPermission dataPermission = new DataPermission(); // 模拟数据=》数据库查询的应该是集合
        List<DataPermission> list = new ArrayList<>();
        dataPermission.setCode("test001")
                .setClassName("org.pearl.springbootsecurity.demo.dao.UserMapper.getUserInfoByUserName")
                .setColumn("bbb")
                .setName("只能查看2021年之后的数据")
                .setField("aaa,bbb,ccc")
                .setValue("u.create_date > \"2021-01-01 00:00:00\"");
        list.add(dataPermission);
        // 2. 根据执行的MS,查询当前有没有配置的数据权限
        DataPermission dbPermission = list.stream().filter(permission -> obj.toString().equals(permission.getClassName())).findAny().orElse(null);
        if (dataPermission == null) {
            throw new DataScopeException("当前用户未查询到数据权限");
        }
        DynamicDataPermission dynamicDataPermission = new DynamicDataPermission();
        dynamicDataPermission.setExpression(dbPermission.getValue());
        dynamicDataPermission.setMapperMethodName(dbPermission.getClassName());
        dynamicDataPermission.setSelectItems(dataPermission.getField());
        return dynamicDataPermission;
    }
}
